#include <board.h>
#include <rtthread.h>
#include "key.h"
#include "rgb.h"
#include <drivers/pin.h>
#include "pwm.h"
#include "rtdevice.h"
#include "uart.h"

extern  rt_flag_t power;
extern rt_uint8_t add_gear_adj;
extern rt_uint8_t subb_gear_adj;
extern rt_uint8_t pwm_data;



struct Key_s{
    uint8_t S1;
    uint8_t S2;
    uint8_t S3;
} Key;

void Key_Init(void){

    Key.S3= rt_pin_get("PF.0");
    Key.S2 = rt_pin_get("PF.1");
    Key.S1 = rt_pin_get("PA.2");
    // 上拉输入
    rt_pin_mode(Key.S1, PIN_MODE_INPUT_PULLUP );
    rt_pin_mode(Key.S2, PIN_MODE_INPUT_PULLUP );
    rt_pin_mode(Key.S3, PIN_MODE_INPUT_PULLUP );
}

int Read_S1(void){
    return rt_pin_read(Key.S1);
}

int Read_S2(void){
    return rt_pin_read(Key.S2);
}

int Read_S3(void){
    return rt_pin_read(Key.S3);
}

void S1_Interrput(void *args){
    rt_kprintf("S1 OK");
     RGB_Red(1);
}

void S2_Interrput(void *args){
    rt_kprintf("S2 OK");
     RGB_Blue(1);
}

void S3_Interrput(void *args){
    rt_kprintf("S3 OK");
    RGB_Green(1);
}

void Key_Interrput_Init(void){
       //中断
}



 void key_thread_entry(void *parameter){
    Key_Init();
    RGB_Init();
    while(1){
        if (Read_S1()==PIN_LOW) {
                rt_thread_mdelay(10);
                while(Read_S1()==PIN_LOW);//等待释放
                  power=~power;
                  if(power)
                  {
                    RGB_Red(power);
                    rt_kprintf("system on\r\n");
                    pwm_vout_adj(35,1);//脉宽是%
                  }
                  else
                  {
                      RGB_Red(power);
                     rt_kprintf("system off\r\n");
                     pwm_vout_adj(pwm_data,0);//脉宽是%
                  }

               }
        else  if (Read_S2()==PIN_LOW) {
            rt_thread_mdelay(10);
           while(Read_S2()==PIN_LOW);//等待释放
           if(power)
           {
               if(pwm_data<35)pwm_data=35;
                         pwm_vout_adj(pwm_data-=5,1);
                        RGB_Green(1);
                        rt_kprintf("down \r\n");
           }
        }
        else if (Read_S3()==PIN_LOW) {
          rt_thread_mdelay(10);
           while(Read_S3()==PIN_LOW);//等待释放
           if(power)
           {
               if(pwm_data>95)pwm_data=95;
                         pwm_vout_adj(pwm_data+=5,1);
                        RGB_Blue(1);
                        rt_kprintf("up \r\n");

                    //    uart_send("uart1", "12345678abcdef");
           }
        }
       rt_thread_mdelay(100);
    }
}
